package online.shenme;

import java.util.Random;
import java.util.Scanner;

//猜数字：
public class guessNum {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random random = new Random();
        int rNum, userNum;

        guess:
        while (true) {
            System.out.println("请输入一个10000以内的正整数");
            while (true) {
                userNum = input.nextInt();
                if (userNum >= 0 && userNum <= 9999) {
                    break;
                } else {
                    System.out.println("该值不在正确的范围，请重新输入");
                }

            }
            System.out.println("计算机猜数字开始：");
            int count = 0, max = 9999, min = 0;
            long start = System.currentTimeMillis();
            while (true) {
                //二分法
//                rNum=(min+max)/2;
                //随机数法
                rNum = random.nextInt((max - min + 1)) + min;
                count++;
                System.out.println("第" + count + "次猜测数字：" + rNum);
                if (rNum == userNum) {
                    System.out.println("猜对了，游戏结束");
                    break;
                } else if (rNum > userNum) {
                    max = rNum-1;
                    System.out.println("猜大了");
                } else {
                    min = rNum+1;
                    System.out.println("猜小了");
                }
                long end = System.currentTimeMillis();
                System.out.println("用时："+(end-start));
            }
            System.out.println("是否重新开始：");
            String charge = input.next();

            switch (charge) {
                default:
                    System.out.println("游戏结束");
                    break guess;
                case "是", "1", "确定", "ok":
                    break;
            }
        }
    }
}
